﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

namespace FSM_Framework.StateMachine
{
    /// <summary>
    /// 串行调度，保证状态迁移时和多线程调用时动作接口时的线程安全
    /// </summary>
    public class SequentialScheduler
    {
        public TransformBlock<WorkItem, object> TransformBlock { get; set; }
        public SequentialScheduler()
        {
            TransformBlock = new TransformBlock<WorkItem, object>(workItem => workItem.Func.Invoke(workItem.Parameter), new ExecutionDataflowBlockOptions() { EnsureOrdered = true, MaxDegreeOfParallelism = 1 });
        }

        internal async Task<object> ExecuteAsyncInternal(Func<object, object> func, object param)
        {

            var workItem = new WorkItem()
            {
                Parameter = param,
                Func = p => func.Invoke(p)
            };
            await TransformBlock.SendAsync(workItem);
            return await TransformBlock.ReceiveAsync();
        }

        public class WorkItem
        {
            public WorkItem()
            {
            }
            public object Parameter { get; set; }
            public Func<object, object> Func { get; set; }

        }
    }




}
